package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.bean.Power;
import org.example.mapper.PowerMapper;
import org.example.service.PowerService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:PowerServiceImpl
 * @Date:2025/8/8 17:26
 */
@Service
public class PowerServiceImpl extends ServiceImpl<PowerMapper, Power> implements PowerService {
    @Resource
    private PowerMapper powerMapper;


    @Override
    public JsonResult FindAllPower() {
        return ResultTool.success(list());
    }

    @Override
    public JsonResult RemovePowerById(String id) {
        return ResultTool.success(powerMapper.FindPowersToUser2(id));
    }

    @Transactional(rollbackFor = Exception.class)
    public JsonResult InsertPowerByIds(String userId, List<String> powers) {
        //1.删除用户权限
        powerMapper.removeByUserIds(userId);
        //2.添加用户权限
        for (String power : powers) {
            QueryWrapper<Power> wrapper = new QueryWrapper<Power>();
            wrapper.eq("name", power);
            Power power1 = getOne(wrapper);
            powerMapper.insertPowerByUserId(userId, power1.getId());
        }
        return ResultTool.success("权限修改成功");
    }
}
